package com.zkdcloud.service;

import com.zkdcloud.domain.*;
import com.zkdcloud.dto.ExtraFee;
import com.zkdcloud.dto.QueryCartCheck;
import com.zkdcloud.dto.TerminalCartInfo;
import com.zkdcloud.repository.*;
import com.zkdcloud.util.RandomUtil;
import org.jfaster.mango.plugin.page.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author zk123
 * @version 2018/5/23
 */
@Service
public class CartService {
    /**
     * cartDao
     */
    @Autowired
    private CartDao cartDao;
    /**
     * cartProductDao
     */
    @Autowired
    private CartProductDao cartProductDao;
    /**
     * businessActiveDao
     */
    @Autowired
    private BusinessActivityDao businessActivityDao;
    /**
     * 购物车折扣
     */
    @Autowired
    private CartDiscountDao cartDiscountDao;
    /**
     * 购物车额外费用
     */
    @Autowired
    private CartExtraDao cartExtraDao;
    /**
     * businessDao
     */
    @Autowired
    private BusinessDao businessDao;
    /**
     * 产品dao
     */
    @Autowired
    private ProductDao productDao;
    /**
     * 计算总价
     *
     * @param queryCartChecks queryCartChecks
     * @return double
     */
    public Double sumPrice(List<QueryCartCheck> queryCartChecks){
        Double result = 0.0d;
        for (QueryCartCheck queryCartCheck : queryCartChecks) {
            result += queryCartCheck.getTotalPrice();
        }
        return result;
    }

    /**
     * 计算额外费用
     *
     * @param businessId businessId
     * @param cartId cartId
     * @return sumExtra
     */
    public Double sumExtra(String businessId,String cartId){
        Business business = businessDao.getOne(businessId);
        //包装费
        Double packageFee = business.getPackageFee();
        if(packageFee > 0){
            CartExtra extraFee = new CartExtra();
            extraFee.setCartId(cartId);
            extraFee.setCreateTime(System.currentTimeMillis());
            extraFee.setDescription("卖家包装费");
            extraFee.setId(RandomUtil.getUUID());
            extraFee.setName("包装费");
            extraFee.setPrice(packageFee);
            cartExtraDao.add(extraFee);
        }

        //配送费
        Double shppingFee = business.getShippingFee();
        if(packageFee > 0){
            CartExtra extraFee = new CartExtra();
            extraFee.setCartId(cartId);
            extraFee.setCreateTime(System.currentTimeMillis());
            extraFee.setDescription("卖家配送费");
            extraFee.setId(RandomUtil.getUUID());
            extraFee.setName("配送费");
            extraFee.setPrice(shppingFee);
            cartExtraDao.add(extraFee);
        }
        return packageFee + shppingFee;
    }
    /**
     * 计算优惠
     *
     * @return value of discount
     */
    public Double sumDiscount(String businessId,String cartId){
        Double result = 0.0D;
        List<BusinessActivity> businessActivities = businessActivityDao.getAllByBid(businessId);
        for (BusinessActivity activity : businessActivities) {
            CartDiscount cartDiscount = new CartDiscount();
            BeanUtils.copyProperties(activity,cartDiscount);

            cartDiscount.setCartId(cartId);
            cartDiscount.setId(RandomUtil.getUUID());
            cartDiscount.setCreateTime(System.currentTimeMillis());
            cartDiscountDao.add(cartDiscount);
            result += activity.getPrice();
        }
        return result;
    }

    /**
     * saveCart
     *
     * @param queryCartChecks queryCart
     * @param queryMap user
     * @return id of cart
     */
    public String saveCart(List<QueryCartCheck> queryCartChecks, Map<String,String> queryMap) throws Exception {
        Cart cart = new Cart();
        cart.setId(RandomUtil.getUUID());
        cart.setBusinessId(queryMap.get("businessId"));
        cart.setPayMethod(queryMap.get("payMethod"));
        //计算总价格，保存额外费用
        cart.setOriginPrice(sumPrice(queryCartChecks) + sumExtra(queryMap.get("businessId"),cart.getId()));
        //计算并保存折扣价
        cart.setDiscountPrice(sumDiscount(queryMap.get("businessId"),queryMap.get("businessId")));
        cart.setTotalPrice(cart.getOriginPrice() - cart.getDiscountPrice());
        cart.setLastAddressId(queryMap.get("lastAddressId"));
        cart.setCreateTime(System.currentTimeMillis()/1000);
        cartDao.add(cart);
        return cart.getId();
    }

    /**
     * 保存购物车产品
     *
     * @param queryCartChecks queryCartChecks
     * @param cartId cartId
     */
    public void saveCartProduct(List<QueryCartCheck> queryCartChecks,String cartId) throws Exception {
        for (QueryCartCheck cartCheck : queryCartChecks) {
            //检查数量是否充裕
            Product product = productDao.getOne(cartCheck.getProduct().getId());
            if(product.getLeftNum() < cartCheck.getQuantity()){
                throw new Exception(product.getName() + "只能购买" + product.getLeftNum() +"份");
            } else {
                //对应相减剩余数量
                product.setLeftNum(product.getLeftNum() - cartCheck.getQuantity());
                product.setMonthSales((product.getMonthSales() == null ? 0 : product.getMonthSales()) + cartCheck.getQuantity());
                productDao.update(product);
                //对应销量增加
                Business business = businessDao.getOne(cartCheck.getProduct().getBusinessId());
                business.setMonthSales((business.getMonthSales() == null ? 0 : business.getMonthSales()) + cartCheck.getQuantity());
                businessDao.update(business);
            }

            CartProduct cartProduct = new CartProduct();
            cartProduct.setId(RandomUtil.getUUID());
            cartProduct.setName(cartCheck.getName());
            cartProduct.setQuantity(cartCheck.getQuantity());
            cartProduct.setTotalPrice(cartCheck.getTotalPrice());
            cartProduct.setUnitPrice(cartCheck.getUnitPrice());
            cartProduct.setProductId(cartCheck.getId());
            cartProduct.setCartId(cartId);
            cartProduct.setCreateTime(System.currentTimeMillis());
            cartProductDao.add(cartProduct);
        }
    }

    /**
     * 根据id获取购物车信息
     *
     * @param id id
     * @return terminalCartInfo
     */
    public TerminalCartInfo getBaseCartInfo(String id){
        TerminalCartInfo result = new TerminalCartInfo();

        //copy originprice ,discountPrice,totalPrice
        Cart cart = cartDao.getOne(id);
        BeanUtils.copyProperties(cart,result);
        result.setBusinessInfo(businessDao.getOne(cart.getBusinessId()));

        //set 设置商品
        List<CartProduct> cartProducts = cartProductDao.getAll(id);
        result.setShoppingProducts(cartProducts);

        //设置额外费用
        List<CartExtra> cartExtraList = cartExtraDao.getAllByCartId(id);
        result.setExtraFees(cartExtraList);

        //设置折扣
        List<CartDiscount> cartDiscountList = cartDiscountDao.getAllByCartId(id);
        result.setDiscountInfos(cartDiscountList);
        return result;
    }

    public List<CartProduct> getCartProductByCartId(String cartId){
        return cartProductDao.getAll(cartId);
    }

}
